package org.example.chatroom.common.config;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2025-06-29
 * Time: 18:58
 */
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;
//自定义一个握手拦截器
public class TokenHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response,
                                   WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        // 1. 从请求中提取 Token（这里示例从查询参数取，也可从请求头取）
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            // 假设前端把token存在浏览器本地
            String token = servletRequest.getServletRequest().getParameter("token");
            if (token != null) {
                // 2. 把 Token 存入 attributes，后续 WebSocketSession 可通过该属性获取
                attributes.put("token", token);
            }
        }
        // 返回 true 允许握手，false 拒绝
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
                               ServerHttpResponse response,
                               WebSocketHandler wsHandler,
                               Exception exception) {
        // TODO 握手完成后可做清理、日志等操作，这里暂时空实现
    }
}